﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using LitJson;
using YamlDotNet.Serialization;
public class EditorAsset
{
    public string fileID;
    public string guid;
}
public static class EditorAssetHelper
{
    static List<List<string>> arrays = new List<List<string>>();
    static List<string> current = null;
    static Deserializer _deserializer;
    static Serializer _serializer;
    static StringBuilder builder = new StringBuilder();
    static Deserializer deserializer
    {
        get
        {
            if (_deserializer == null)
            {
                _deserializer = new DeserializerBuilder().Build();
            }
            return _deserializer;
        }
    }

    static Serializer serializer
    {
        get
        {
            if (_serializer == null)
            {
                _serializer = new SerializerBuilder().JsonCompatible().Build();
            }
            return _serializer;
        }
    }


    public static EditorAsset[] GetEditorAsset(string path)
    {
        arrays.Clear();
        var lines = File.ReadAllLines(path);
        for (int i = 2; i < lines.Length; i++)
        {
            var line = lines[i];
            if (line.IndexOf("--- !u!") != -1)
            {
                current = new List<string>();
                arrays.Add(current);
            }
            current.Add(line);
        }

        List<EditorAsset> result = new List<EditorAsset>();
        foreach (var list in arrays)
        {
            builder.Length = 0;
            for (var i = 1; i < list.Count; i++)
            {
                builder.AppendLine(list[i]);
            }
            var yamlObject = deserializer.Deserialize(new StringReader(builder.ToString()));
            var json = serializer.Serialize(yamlObject);

            var array = list[0].Substring(7).Trim().Split('&');
            var unityType = int.Parse(array[0]);
            var id = long.Parse(array[1]);

            if (unityType != 114)
                continue;

            var jsonData = JsonMapper.ToObject(json);
            foreach (KeyValuePair<string, JsonData> pair in jsonData[0])
            {
                if (pair.Key == "m_Script")
                {
                    var fileid = pair.Value["fileID"].ToString();
                    var guid = pair.Value["guid"].ToString();
                    result.Add(new EditorAsset { fileID = fileid, guid = guid });
                }
            }
        }
        return result.ToArray();
    }
}
